#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理模块
负责管理应用程序的设置和配置
"""

import json
import os
from typing import Dict, Any


class Config:
    """配置管理类"""
    
    def __init__(self, config_file="config.json"):
        self.config_file = config_file
        self.default_config = {
            # 录制设置
            'recording': {
                'mouse_threshold': 0.01,  # 鼠标移动记录间隔（秒）
                'key_threshold': 0.01,    # 按键记录间隔（秒）
                'auto_save': False,       # 自动保存录制
                'save_directory': 'scripts'  # 保存目录
            },
            
            # 播放设置
            'playback': {
                'default_speed': 1.0,     # 默认播放速度
                'pause_between_loops': 1.0,  # 循环间隔时间
                'confirm_before_play': True,  # 播放前确认
                'stop_on_error': True,    # 出错时停止
                'default_script': None    # 默认脚本名称
            },
            
            # UI设置
            'ui': {
                'window_width': 600,      # 窗口宽度
                'window_height': 500,     # 窗口高度
                'theme': 'default',       # 主题
                'language': 'zh_CN',      # 语言
                'remember_position': True  # 记住窗口位置
            },
            
            # 快捷键设置
            'hotkeys': {
                'start_recording': 'F9',   # 开始录制
                'stop_recording': 'F10',   # 停止录制
                'play_script': 'F11',      # 播放脚本
                'stop_playing': 'F12',     # 停止播放
                'emergency_stop': 'Esc'    # 紧急停止
            },
            
            # 高级设置
            'advanced': {
                'max_operations': 10000,   # 最大操作数
                'backup_scripts': True,    # 备份脚本
                'log_level': 'INFO',       # 日志级别
                'enable_statistics': True  # 启用统计
            }
        }
        
        self.config = self.default_config.copy()
        self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                
                # 合并配置，保留默认值
                self._merge_config(self.config, loaded_config)
                print(f"配置已从 {self.config_file} 加载")
            else:
                print("配置文件不存在，使用默认配置")
                self.save_config()  # 创建默认配置文件
        
        except Exception as e:
            print(f"加载配置失败: {e}，使用默认配置")
            self.config = self.default_config.copy()
    
    def save_config(self):
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
            print(f"配置已保存到 {self.config_file}")
            return True
        except Exception as e:
            print(f"保存配置失败: {e}")
            return False
    
    def _merge_config(self, default_dict, loaded_dict):
        """递归合并配置字典"""
        for key, value in loaded_dict.items():
            if key in default_dict:
                if isinstance(value, dict) and isinstance(default_dict[key], dict):
                    self._merge_config(default_dict[key], value)
                else:
                    default_dict[key] = value
    
    def get(self, key_path, default=None):
        """获取配置值
        
        Args:
            key_path: 配置路径，如 'recording.mouse_threshold'
            default: 默认值
        
        Returns:
            配置值
        """
        keys = key_path.split('.')
        value = self.config
        
        try:
            for key in keys:
                value = value[key]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key_path, value):
        """设置配置值
        
        Args:
            key_path: 配置路径，如 'recording.mouse_threshold'
            value: 配置值
        """
        keys = key_path.split('.')
        config_dict = self.config
        
        # 导航到目标字典
        for key in keys[:-1]:
            if key not in config_dict:
                config_dict[key] = {}
            config_dict = config_dict[key]
        
        # 设置值
        config_dict[keys[-1]] = value
    
    def reset_to_default(self):
        """重置为默认配置"""
        self.config = self.default_config.copy()
        print("配置已重置为默认值")
    
    def get_recording_config(self):
        """获取录制相关配置"""
        return self.config.get('recording', {})
    
    def get_playback_config(self):
        """获取播放相关配置"""
        return self.config.get('playback', {})
    
    def get_ui_config(self):
        """获取UI相关配置"""
        return self.config.get('ui', {})
    
    def get_hotkeys_config(self):
        """获取快捷键配置"""
        return self.config.get('hotkeys', {})
    
    def get_advanced_config(self):
        """获取高级配置"""
        return self.config.get('advanced', {})
    
    def update_recording_config(self, **kwargs):
        """更新录制配置"""
        recording_config = self.config.setdefault('recording', {})
        recording_config.update(kwargs)
    
    def update_playback_config(self, **kwargs):
        """更新播放配置"""
        playback_config = self.config.setdefault('playback', {})
        playback_config.update(kwargs)
    
    def update_ui_config(self, **kwargs):
        """更新UI配置"""
        ui_config = self.config.setdefault('ui', {})
        ui_config.update(kwargs)
    
    def update_hotkeys_config(self, **kwargs):
        """更新快捷键配置"""
        hotkeys_config = self.config.setdefault('hotkeys', {})
        hotkeys_config.update(kwargs)
    
    def update_advanced_config(self, **kwargs):
        """更新高级配置"""
        advanced_config = self.config.setdefault('advanced', {})
        advanced_config.update(kwargs)
    
    def validate_config(self):
        """验证配置的有效性
        
        Returns:
            tuple: (is_valid, error_messages)
        """
        errors = []
        
        # 验证录制配置
        recording = self.get_recording_config()
        if recording.get('mouse_threshold', 0) < 0:
            errors.append("鼠标记录间隔不能为负数")
        if recording.get('key_threshold', 0) < 0:
            errors.append("按键记录间隔不能为负数")
        
        # 验证播放配置
        playback = self.get_playback_config()
        if playback.get('default_speed', 1.0) <= 0:
            errors.append("播放速度必须大于0")
        if playback.get('pause_between_loops', 0) < 0:
            errors.append("循环间隔不能为负数")
        
        # 验证UI配置
        ui = self.get_ui_config()
        if ui.get('window_width', 600) < 400:
            errors.append("窗口宽度不能小于400")
        if ui.get('window_height', 500) < 300:
            errors.append("窗口高度不能小于300")
        
        # 验证高级配置
        advanced = self.get_advanced_config()
        if advanced.get('max_operations', 10000) < 100:
            errors.append("最大操作数不能小于100")
        
        return len(errors) == 0, errors
    
    def export_config(self, filename):
        """导出配置到指定文件
        
        Args:
            filename: 导出文件名
        
        Returns:
            bool: 是否成功
        """
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
            print(f"配置已导出到 {filename}")
            return True
        except Exception as e:
            print(f"导出配置失败: {e}")
            return False
    
    def import_config(self, filename):
        """从指定文件导入配置
        
        Args:
            filename: 导入文件名
        
        Returns:
            bool: 是否成功
        """
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                imported_config = json.load(f)
            
            # 验证导入的配置
            temp_config = self.default_config.copy()
            self._merge_config(temp_config, imported_config)
            
            # 如果验证通过，应用配置
            self.config = temp_config
            print(f"配置已从 {filename} 导入")
            return True
        
        except Exception as e:
            print(f"导入配置失败: {e}")
            return False
    
    def get_config_summary(self):
        """获取配置摘要
        
        Returns:
            str: 配置摘要文本
        """
        recording = self.get_recording_config()
        playback = self.get_playback_config()
        ui = self.get_ui_config()
        
        summary = f"""配置摘要:
录制设置:
  - 鼠标记录间隔: {recording.get('mouse_threshold', 0.01)}秒
  - 按键记录间隔: {recording.get('key_threshold', 0.01)}秒
  - 自动保存: {'是' if recording.get('auto_save', False) else '否'}
  - 保存目录: {recording.get('save_directory', 'scripts')}

播放设置:
  - 默认播放速度: {playback.get('default_speed', 1.0)}x
  - 循环间隔: {playback.get('pause_between_loops', 1.0)}秒
  - 播放前确认: {'是' if playback.get('confirm_before_play', True) else '否'}

UI设置:
  - 窗口大小: {ui.get('window_width', 600)}x{ui.get('window_height', 500)}
  - 主题: {ui.get('theme', 'default')}
  - 语言: {ui.get('language', 'zh_CN')}"""
        
        return summary
    
    def __str__(self):
        """字符串表示"""
        return f"Config(file={self.config_file})"
    
    def __repr__(self):
        """详细字符串表示"""
        return f"Config(file={self.config_file}, config={self.config})"